﻿using System;
using System.IO;
using MathematicallySafe.HeadCounter.Data;
using MathematicallySafe.HeadCounter.Data.Interfaces;
using MathematicallySafe.Utilities;
using StructureMap;

namespace MathematicallySafe.HeadCounter.Services.Backup
{
    public class BackupService: IBackupService
    {
        private static readonly IUserOptions UserOptions = ObjectFactory.GetInstance<IUserOptions>();

        private readonly SimpleArchiveTool _archiver = new SimpleArchiveTool();
        private readonly ArchiveManager _archiveManager = new ArchiveManager();

        private string _dataLocation;
        private string _archiveLocation;

        public string DataLocation
        {
            get { return _dataLocation; }
            set
            {
                _dataLocation = value;
                _dataLocation = EnsureTrailingSlash(_dataLocation);
            }
        }

        public string DataWildcard { get; set; }

        public string ArchiveLocation
        {
            get { return _archiveLocation; }
            set
            {
                _archiveLocation = value;
                _archiveLocation = EnsureTrailingSlash(_archiveLocation);
            }
        }

        public string ArchiveName { get; set; }

        public void Backup()
        {
            _archiveManager.ArchiveLocation = ArchiveLocation;

            var archiveName = ArchiveLocation;
            if (string.IsNullOrEmpty(ArchiveName))
            {
                archiveName += _archiveManager.GenerateName();
            }
            else
            {
                archiveName += ArchiveName;
            }

            _archiver.MakeArchive(archiveName, DataLocation + DataWildcard);
            _archiveManager.TrimArchive(UserOptions.MaxBackups);

            OnBackupComplete();
        }

        public event Action BackupComplete;

        private void OnBackupComplete()
        {
            if (BackupComplete != null)
            {
                BackupComplete();
            }
        }

        #region Helpers

        private string EnsureTrailingSlash(string directoryName)
        {
            if (!directoryName.EndsWith("/")) directoryName += "/";
            return directoryName;
        }

        #endregion
    }
}